<template>
  <div class="editable">
    <el-input
      v-model="val"
      v-if="edit"
      size="small"
      @blur="toggleEdit">
    </el-input>
    <!-- TODO: 现在还只有blur能成功触发，用户体验还需要进一步改善 -->
    <span v-else @dblclick="toggleEdit">
      {{ val }}
    </span>
  </div>
</template>

<script>
export default {
  name: 'cl-editable',
  props: {
    value: {
      required: true
    }
  },
  data () {
    return {
      val: '',
      edit: false
    }
  },
  methods: {
    toggleEdit () {
      this.edit = !this.edit
      if (this.edit === false) {
        this.$emit('toggle')
      }
    }
  },
  created () {
    this.val = this.value
  },
  watch: {
    val (v, ov) {
      this.$emit('change', v, ov)
    },
    value (v, ov) {
      this.val = v
    }
  }
}
</script>
